package com.pms.api;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.controller.BaseController;
import com.pms.entity.BaseUser;
import com.pms.entity.CompanyCode;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.IBaseGroupService;
import com.pms.service.IBaseUserService;
import com.pms.service.ICompanyCodeService;
import com.pms.util.SmSUtile;
import com.pms.util.WebUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 *  前端控制器
 * @author zyl
 * @since 2017-07-06
 */
@RestController
@RequestMapping("/api/user")
@Api(value = "APP用户管理",description = "APP用户管理")
public class ApiBaseUserController extends BaseController {
    @Autowired
    IBaseUserService baseUserService;
    @Autowired
    com.pms.cache.utils.RedisCacheUtil RedisCacheUtil;
    @Autowired
    ICompanyCodeService companyCodeService;
    @Autowired
    IBaseGroupService baseGroupService;

    /**
     * 联系我们接口
     * @param companyCode
     * @return
     */
    @ApiOperation(value = "联系我们接口")
    @GetMapping(value="/selectByCompanyPhone")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyCode", value = "公司编码", required = true, dataType = "String", paramType = "form"),
    })
    public R selectByCompanyPhone(String  companyCode){
        parameterIsNull(companyCode,"公司编码不能为空");
        CompanyCode code =companyCodeService.selectOne(new EntityWrapper<CompanyCode>().eq("company_code",companyCode));
        return  R.ok().put("data",code);
    }
    /**
     * 查询我的用户信息
     * @param id
     * @return
     */
    @ApiOperation(value = "查询我的用户信息")
    @GetMapping(value="/findById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "form"),
            })
    public R findById(Long id){
        parameterIsNull(id,"ID不能为空");
        BaseUser user =baseUserService.selectByPerssId(id);
        parameterIsNull(user,"用户信息不存在");
        user.setPassword(null);
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("user",user);
        return R.ok().put("data",map).putDescription(BaseUser.class);
    }

    /**
     * 发送验证码(阿里云短信）
     * @param request
     * @param phone
     * @param type
     * @param companyCode
     * @return
     */
    @ApiOperation(value = "发送验证码(阿里云短信)")
    @PostMapping(value="/aliyun/smsCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "companyCode", value = "公司编码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "验证类型(1.用户注册2.身份验证3.修改密码4.身份变更5.登录异常6.快速注册7.修改支付密码)", required = true, dataType = "String", paramType = "form"),
    })
    public R aliyunGetSmsCode(HttpServletRequest request, String phone, String type,String companyCode){
        parameterIsBlank(phone,"手机号码不能为空");
        parameterIsBlank(companyCode,"公司编码不能为空");
        parameterIsBlank(type,"验证类型不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
        BaseUser user;
        if (type.equals("1")){//注册
            user=baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("mobile_phone",phone).and().eq("company_code",companyCode));
            if (user!=null){
                throw  new RRException("该账号已被注册，请重新输入账号！",400);
            }
        }else if(type.equals("4")){//身份变更
            user=baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("mobile_phone",phone).and().eq("company_code",companyCode));
            if (user!=null){
                throw  new RRException("该账号已被注册，请重新输入账号！",400);
            }
        }else{
            user=baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("mobile_phone",phone).and().eq("company_code",companyCode));
            parameterIsNull(user,"该账号尚未被注册，请重新输入账号");
        }
        String   smsCode = SmSUtile.sendSms(phone, Integer.parseInt(type), null);
        if (smsCode.equals("error")){ return R.error("对不起！该手机号一分钟不能超过一条，请稍等一分钟后再试！");}
        if (StringUtils.isNotBlank(smsCode)) {
            if (Integer.valueOf(smsCode) <= 0) {
                smsCode = "0";
            }
            RedisCacheUtil.saveAndUpdate(phone + "API_PMS_RegisterSMSCode",smsCode,10);
            return R.ok().put("codes",smsCode);
        } else {
            smsCode = "0";
        }
        return R.ok();
    }

    /**
     * 验证码匹对
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/Verification")
    @ApiOperation(value = "验证码匹对", notes = "验证码匹对")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", paramType = "form", dataType = "String"),
    })
    public R Verification(String phone, String code) {
        Assert.isBlank(code, "验证码不能为空");
        parameterIsBlank(phone,"手机号码不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请从新输入！");}
        Object SMSCode= RedisCacheUtil.getVlue(phone + "API_PMS_RegisterSMSCode");
        if(SMSCode==null){ return R.error("输入验证码已失效！"); }
        if (code != null && code.equals(SMSCode.toString())) {
            RedisCacheUtil.clearByKey(phone + "API_PMS_RegisterSMSCode");
            return R.ok();
        }else{
            return R.error("输入验证码不正确！");
        }
    }
    /**
     * 修改会员头像
     * @param id
     * @param imgUrl
     * @return
     */
    @PostMapping("/updateByImgUrl")
    @ApiOperation(value = "修改用户头像", notes = "修改用户头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", paramType = "form", dataType = "Long"),
            @ApiImplicitParam(name = "imgUrl", value = "会员头像", paramType = "form", dataType = "String")
    })
    public R updateByImgUrl(Long id, String imgUrl) {
        Assert.parameterIsNull(id, "memberId会员ID不能为空");
        Assert.isBlank(imgUrl, "会员头像不能为空");
        BaseUser user = baseUserService.selectById(id);
        if (user !=null ){
            user.setImg(imgUrl);
            baseUserService.updateById(user);
            return R.ok();
        }else{
            return R.error("该会员信息不存在！");
        }
    }

    /**
     * 修改账户密码
     * @param phone
     * @param oldpassWord
     * @param companyCode
     * @param newpassWord
     * @return
     */
    @PostMapping("/updateUserPassWord")
    @ApiOperation(value = "修改账户密码", notes = "修改账户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "oldpassWord", value = "原密码", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "newpassWord", value = "新密码", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "companyCode", value = "公司编码", required = true, dataType = "String", paramType = "form")
    })
    public R updateUserPassWord(String phone, String oldpassWord,String companyCode,String newpassWord) {
        Assert.isBlank(phone, "手机号不能为空");
        Assert.isBlank(oldpassWord, "原密码不能为空");
        parameterIsBlank(newpassWord,"新密码不能为空");
        parameterIsBlank(companyCode,"公司编码不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
        BaseUser user=baseUserService.selectbyCompanyCode(phone,companyCode);
        parameterIsNull(user,"该账号尚未被注册，请重新输入手机号");
        if (!user.getPassword().equals(BCrypt.hashpw(oldpassWord,user.getPassword()))){
            return  R.error(400,"原密码不正确，请重新输入");
        }
        user.setPassword(BCrypt.hashpw(newpassWord,user.getPassword()));
        baseUserService.updateById(user);
        return R.ok();
    }
    /**
     * 修改手机号
     * @param phone
     * @param code
     * @param companyCode
     * @return
     */
    @PostMapping("/updatePhone")
    @ApiOperation(value = "修改手机号", notes = "修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPhone", value = "原手机号", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "companyCode", value = "公司编码", required = true, dataType = "String", paramType = "form")
    })
    public R updatePhone(String oldPhone,String phone, String code,String companyCode) {
        Assert.isBlank(oldPhone, "原手机号不能为空");
        Assert.isBlank(phone, "手机号不能为空");
        Assert.isBlank(code, "验证码不能为空");
        parameterIsBlank(companyCode,"公司编码不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
        BaseUser mobilePhone=  baseUserService.selectByUser(companyCode,phone,phone);
        if (mobilePhone !=null){throw  new RRException("已有相同手机号存在，请重新输入",400); }
        Object SMSCode= RedisCacheUtil.getVlue(phone + "API_PMS_RegisterSMSCode");
        if(SMSCode==null){ return R.error("输入验证码已失效！"); }
        if (code != null && code.equals(SMSCode.toString())) {
            RedisCacheUtil.clearByKey(phone + "API_PMS_RegisterSMSCode");
            BaseUser user=baseUserService.selectbyCompanyCode(oldPhone,companyCode);
            parameterIsNull(user,"该账号尚未被注册，请重新输入手机号");
            user.setMobilePhone(phone);
            baseUserService.updateById(user);
            return R.ok();
        }else{
            return R.error("输入验证码不正确！");
        }
    }
}

